package cn.lliiooll.mtlib;

import cn.lliiooll.mtlib.command.BukkitCommand;
import cn.lliiooll.mtlib.listener.BukkitListener;
import cn.lliiooll.mtlib.utils.JarUtils;
import lombok.SneakyThrows;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.TabCompleter;
import org.bukkit.command.TabExecutor;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

import java.lang.reflect.Method;

public class MTlib {

    @SneakyThrows
    public static void init(JavaPlugin plugin) {
        JarUtils.scanByPackage();
        for (Class<?> clazz : JarUtils.getAllLoadClasses()) {
            // 自动注册监听器
            if (clazz.getAnnotation(BukkitListener.class) != null) {// 保证含有Listener注解
                for (Class<?> infs : clazz.getInterfaces()) {
                    if (infs == Listener.class) {// 保证有listener接口
                        Bukkit.getPluginManager().registerEvents((Listener) clazz.newInstance(), plugin);
                    }
                }
            } else if (clazz.getAnnotation(BukkitCommand.class) != null) {// 保证有BukkitCommand注解
                for (Class<?> infs : clazz.getInterfaces()) {
                    BukkitCommand cmd = clazz.getAnnotation(BukkitCommand.class);
                    if (infs == TabExecutor.class) {// 多写一个来防止可能发生的错误
                        Bukkit.getPluginCommand(cmd.name()).setTabCompleter((TabExecutor) clazz.newInstance());
                    }
                    if (infs == TabCompleter.class) {// 使TabCompleter在前保证他先被检测到
                        Bukkit.getPluginCommand(cmd.name()).setTabCompleter((TabCompleter) clazz.newInstance());
                    }
                    if (infs == CommandExecutor.class) {// 保证有CommandExecutor接口
                        Bukkit.getPluginCommand(cmd.name()).setExecutor((CommandExecutor) clazz.newInstance());
                    }
                }
            }
        }
    }
}
